require 'quick_magick'
require 'find'

class Book < ActiveRecord::Base
  has_many :regions
  has_many :bookmarks
  has_many :pages, :dependent => :destroy
  
  attr_accessor :pdf_file

  def pdf_file_name
    File.join(PDF_BOOKS_DIR,"%03d.pdf"%(id))
  end
  
  def number_of_pages
    pages.length
  end
  
  def after_destroy
    delete_all_images
    delete_all_sounds
    delete_pdf_file    
  end
  
  def after_save
    if pdf_file
      save_pdf_file
      delete_all_images
      generate_all_images
    end
  end
  
protected

  def save_pdf_file
    File.open(pdf_file_name, "wb") do |f|
      f.write pdf_file
    end
  end
  
  def delete_pdf_file
    File.delete(pdf_file_name) if File.exists?(pdf_file_name)
  end

  def generate_all_images
    # Generate new images using ImageMagick
    pages.destroy_all
    pdf_file_images = QuickMagick::Image.read(pdf_file_name)
    pdf_file_images.each_with_index { |image, index|
      # We add (1) because images in ImageList are 0-based while pages are 1-based
      p = pages[index] || pages.new
      p.page_number = index + 1
      p.save
      image.write(p.image_file_name)
    }
    if pages.length > pdf_file_images.length
      pages[pdf_file_images.length .. pages.length].each do |page|
        page.destroy
      end
    end
  end
  
  def delete_all_images
    # Delete any old generate images for this book
    Find.find(PDF_BOOKS_DIR) do |file|
      if /#{id}\.\d+\.jpg/ =~ file
        File.delete(file)
      end
    end
  end
  
  def delete_all_sounds
    # Delete any old generate images for this book
    Find.find(PDF_BOOKS_DIR) do |file|
      if /#{id}\.\d+\.mp3/ =~ file
        File.delete(file)
      end
    end
  end

end
